from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import McClinic
from .serializers import McClinicSerializer

@api_view(['GET'])
def clinic_list(request):
    items = McClinic.objects.all().order_by('-created_time')
    serializer = McClinicSerializer(items, many=True)
    return Response(serializer.data)

@api_view(['GET'])
def clinic_detail(request, pk):
    try:
        item = McClinic.objects.get(pk=pk)
    except McClinic.DoesNotExist:
        return Response({'error': 'Not found'}, status=status.HTTP_404_NOT_FOUND)
    serializer = McClinicSerializer(item)
    return Response(serializer.data)

@api_view(['POST'])
def clinic_create(request):
    serializer = McClinicSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['PUT'])
def clinic_update(request, pk):
    try:
        item = McClinic.objects.get(pk=pk)
    except McClinic.DoesNotExist:
        return Response({'error': 'Not found'}, status=status.HTTP_404_NOT_FOUND)
    serializer = McClinicSerializer(item, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['DELETE'])
def clinic_delete(request, pk):
    try:
        item = McClinic.objects.get(pk=pk)
    except McClinic.DoesNotExist:
        return Response({'error': 'Not found'}, status=status.HTTP_404_NOT_FOUND)
    item.delete()

    print("进入 my_view 视图")
    print("请求参数：", item)
    return Response(status=status.HTTP_204_NO_CONTENT)
